<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');
class SCTV_MaintenanceSmsCommon extends ModuleCommon{
    public static function menu() {
        return array(__('SCTV') => array(
            '__submenu__' => 1, __('BẢO TRÌ') => array(
    			'__submenu__' => 2, __('Send Maintenance SMS') => array()
        )));
    }
    public static function cron(){
        //self::cron2();
        return array('cron1'=>0);
    }
	public static function cron1(){
        $dbconn=pg_connect("host=localhost port=5432 dbname=sms user=postgres password=admin");
        $results=pg_query($dbconn,"select * from in_get('MBT', 4)");
        $results=pg_fetch_all($results);
        if($results != null){
            foreach($results as $key=>$sms){
                $id = $sms['id'];
                $sender = $sms['sender'];
                $msg = $sms['msg'];
                $msg_date = $sms['msg_date'];
                $msg_time = $sms['msg_time'];

                $contacts = Utils_RecordBrowserCommon::get_records('contact', array('|mobile_phone_sms'=>$sender, '|mobile_phone_sms_1'=>$sender));
                if(empty($contacts)){ // Không có trong danh sách nhân viên
                    pg_query_params($dbconn,"select in_update_read_counter($1)",array($id));
                }
                else{
                    $contact = array_shift($contacts);
                    $contact_id = $contact['id'];
                    // Kiem tra so dien thoai co phai la cua nhan vien lap dat khong
                    if(array_key_exists('Technical', $contact['group'])){
                        $results = self::processing_sms($contact_id, $msg_date, $msg);
                        print_r($results);
                        if(array_key_exists('MBT', $results)) $mbt = $results['MBT']['ID'];
                        else $mbt = '';

                        Utils_RecordBrowserCommon::new_record('SCTV_MaintenanceRequirementSms', array(
                            'in_out'=>1,
                            'maintenance'=>$mbt,
                            'sms_id'=>$id,
                            'employee'=>$contact['id'],
                            'phone_number'=>$sender,
                            'content'=>$msg,
                            'date'=>$msg_date,
                            'time'=>$msg_date . ' ' . $msg_time
                        ));

                        if($results[0] === false){
                            self::send_out($dbconn, $sender, 'MBT#' . $mbt . ': ' . $results[1], 'MBT', $mbt, $contact_id);
                        }
                        else{
                            $sms_code = $results['MBT']['SMS_CODE'];
                            if($sms_code == 'NT'){
                                $results = self::valid_and_save_acceptance($msg_date, $msg_time, $contact, $results);
                                print_r($results);
								print_r($results['service'] );
								sleep(15);
                                if($results[0] === false){
                                    self::send_out($dbconn, $sender, 'MBT#' . $mbt . ': ' . $results[1], 'MBT', $mbt, $contact_id);
                                }
                                else{
                                    self::send_out($dbconn, $sender, 'MBT#' . $mbt . ': nghiem thu bao tri thanh cong!' , 'MBT', $mbt, $contact_id);
                                }
                            }
                            elseif($sms_code == 'TT'){
                                $results = self::valid_and_change_status($msg_date, $msg_time, $contact, $results);
                                print_r($results);
                                if($results[0] === false){
                                    self::send_out($dbconn, $sender, 'MBT#' . $mbt . ': ' . $results[1], 'MBT', $mbt, $contact_id);
                                }
                                else{
                                    self::send_out($dbconn, $sender, 'MBT#' . $mbt . ': da doi trang thai ' . Utils_CommonDataCommon::get_value('SCTV/Maintenance/Status/' . $results['TT'], true), 'MBT', $mbt, $contact_id);
                                }
                            }
                            elseif($sms_code == 'NGAYHEN'){
                                $results = self::valid_and_change_delivery_date($msg_date, $msg_time, $contact, $results);
                                print_r($results);
                                if($results[0] === false){
                                    self::send_out($dbconn, $sender, 'MBT#' . $mbt . ': ' . $results[1], 'MBT', $mbt, $contact_id);
                                }
                                else{
                                    self::send_out($dbconn, $sender, 'MBT#' . $mbt . ': da thay doi ngay hen ' . date('d/m/Y', strtotime($results['NGAY'])), 'MBT', $mbt, $contact_id);
                                }
                            }
                        }
                        echo '<hr>';

                        pg_query_params($dbconn,"select in_update_read_counter($1)",array($id));
                    }
                    else{
                        pg_query_params($dbconn,"select in_update_read_counter($1)",array($id));
                    }
                }
            }
        }
        pg_close($dbconn);
	}

    private static function processing_sms($technical, $msg_date, $msg)
    {
        $result = array();
        $parts = explode(',', $msg);
        $mbt = self::parse_mbt($parts[0]);
        if($mbt === false){
            $result = array(false, 'Sai cu phap MBT');
        }
        else{
            // kiem tra ma bao tri
            $maintenance = Utils_RecordBrowserCommon::get_record('SCTV_Maintenance', $mbt);
            if($maintenance == null){
                $result = array(false, 'khong co', 'MBT' => array('ID'=>$mbt));
            }
            else{
                $status = $maintenance['status'];
                $command_type = self::check_command_type($parts);

                switch($command_type){
                    case 'NT':
                        if($status == 0 || $status == 3){
                            if(self::check_maintenance_technical($mbt, $technical, $status==0?$msg_date:null))
                                $result = self::parse_nt($parts);
                            else
                                $result = array(false, 'khong duoc giao cho anh');
                        }
                        else{
                            $result = array(false, 'da duoc chot truoc day');
                        }
                        break;
                    case 'TT':
                        if($status == 0){
                            if(self::check_maintenance_technical($mbt, $technical, $msg_date)){
                                $result = self::parse_tt($parts);
                                $result['MBT'] = array('ID'=>$mbt, 'SMS_CODE'=>$command_type, 'STATUS'=>$status);
                            }
                            else{
                                $result = array(false, 'khong duoc giao cho anh');
                            }
                        }
                        else{
                            $result = array(false, 'da duoc chot truoc day');
                        }
                        break;
                    case 'NGAYHEN':
                        if($status == 0){
                            if(self::check_maintenance_technical($mbt, $technical, $msg_date)){
                                $result = self::parse_ngayhen($parts);
                                $result['MBT'] = array('ID'=>$mbt, 'SMS_CODE'=>$command_type, 'STATUS'=>$status);
                            }
                            else{
                                $result = array(false, 'khong duoc giao cho anh');
                            }
                        }
                        else{
                            $result = array(false, 'da duoc chot truoc day');
                        }
                        break;
                    default:
                        $result = array(false, 'khong nhan ra cu phap');
                        break;
                }
                $result['MBT'] = array('ID'=>$mbt, 'SMS_CODE'=>$command_type, 'STATUS'=>$status);
            }
        }

        return $result;
    }
    private static function pre_processing($part, $replace_space = true, $upper = true, $beginning_trim = false){
        if($replace_space) $part = str_replace(' ', '', $part);
        if($upper) $part = strtoupper($part);
        if($beginning_trim) $part = ltrim($part);
        return $part;
    }
    private static function parse_mbt($mbt){
        $mbt = self::pre_processing($mbt);
        if(preg_match("/^MBT\(([0-9]+)\)$/", $mbt, $matches))
        {
            return $matches[1];
        }
        else return false;
    }
    private  static function parse_nt($parts)
    {
        $result = array();

        $dtbt = self::parse_dtbt($parts[1]);
        if($dtbt[0] === false){
            $result = $dtbt;
        }
        else{
            $tbbt = self::parse_tbbt($parts[2]);
            if($tbbt[0] === false){
                $result = $tbbt;
            }
            else{
                $ghichu = self::parse_gc($parts[3]);
                if($ghichu[0] === false){
                    $result = $ghichu;
                }
                else{
                    return array(true, 'DTBT'=>$dtbt, 'TBBT'=>$tbbt, 'GHICHU'=>$ghichu);
                }
            }
        }

        return $result;
    }
    private  static function parse_tt($parts)
    {
        $result = array(false);
        $part1 = self::pre_processing($parts[1]);
        if(preg_match("/^TT\(([0-9]+)\)$/", $part1, $matches_tt)){
            $tt = $matches_tt[1];
            if($tt >= 2 && $tt <= 15){
                $part2 = self::pre_processing($parts[2], false, true, true);
                if(preg_match("/^GC\((.+)\)/", $part2, $matches_gc)){
                    $ghichu = $matches_gc[1];
                    if($ghichu == 'X') $ghichu = null;
                    $result = array(true, 'TT'=>$tt, 'GHICHU'=>$ghichu);
                }
                else
                    $result = array(false, 'thieu ghi chu');
            }
            else
                $result = array(false, 'ma trang thai khong dung');
        }
        else{
            $result = array(false, 'sai cu phap TT');
        }

        return $result;
    }
    private  static function parse_ngayhen($parts)
    {
        $result = array(false);
        $part1 = self::pre_processing($parts[1]);

        if(preg_match("/^NGAYHEN\(([0-9]+)\:([0-9]+)\:([0-9]+)\)$/", $part1, $matches)){
            if(checkdate($matches[2], $matches[1], $matches[3])){
                $date = date('Y-m-d', mktime(0,0,0,$matches[2], $matches[1], $matches[3]));
                if($date >= date('Y-m-d'))
                {
                    $part2 = self::pre_processing($parts[2], false, true, true);
                    if(preg_match("/^GC\((.+)\)/", $part2, $matches)){
                        $ghichu = $matches[1];
                        if($ghichu == 'X') $ghichu = null;
                        $result = array(true, 'NGAY'=>$date, 'GHICHU'=>$ghichu);
                    }
                    else
                        $result = array(true, 'NGAY'=>$date);
                }
                else{
                    $result = array(false, 'sai ngay hen');
                }
            }
            else{
                $result = array(false, 'ngay hen khong dung');
            }
        }
        else{
            $result = array(false, 'sai cu phap NGAYHEN');
        }

        return $result;
    }
    private  static function parse_dtbt($part)
    {
        $result = array(false);
        $part = self::pre_processing($part);
        if(preg_match("/^DTBT\((X|KH|DT)\)$/", $part, $matches)){
            $result = array(true, 'DTBT'=>$matches[1]);
		}
		else{
            $result = array(false, 'Sai cu phap DTBT');
        }
        return $result;
    }
    private static function parse_tbbt($part)
    {
        $result = array(false);
        $part = self::pre_processing($part);
        if(preg_match("/^TBBT\(([a-zA-Z0-9\:\/]+)\)$/", $part, $matches)){
            $children = explode('/', $matches[1]);
            if(count($children) == 2){
                if(preg_match("/^THC:(X|1)$/", $children[0], $matches_thc)){
                    if(preg_match("/^NET:(X|1)$/", $children[1], $matches_net)){
						$result = array(true, 'THC'=>$matches_thc[1], 'NET'=>$matches_net[1]);
					}
					else{
						$result = array(false, 'Sai gia tri NET');
					}
                }
                else{
                    $result = array(false, 'Sai gia tri THC');
                }
            }
            else{
                $result = array(false, 'Sai noi dung TBBT');
            }
        }
        else{
            $result = array(false, 'Sai cu phap TBBT');
        }

        return $result;
    }
    private static function parse_gc($part){
        $result = array(false);
        $part = self::pre_processing($part);
        if(preg_match("/^GC\((.+)\)$/", $part, $matches_gc)){
			$ghichu = $matches_gc[1];
            if($ghichu == 'X') $ghichu = null;
            $result = array(true, 'GHICHU'=>$ghichu);
        }
        else{
            $result = array(false, 'thieu ghi chu');
        }

        return $result;
    }
    
    private static function check_maintenance_technical($maintenance, $technical, $date){
        if($date == null){ // Kiem tra khong theo ngay, lay record cuoi cung
            $records = Utils_RecordBrowserCommon::get_records('SCTV_MaintenanceDeployment', array('maintenance'=>$maintenance), array(), array('date'=>'desc'), 1);
            if(empty($records))
                return false;
            else{
                $record = array_shift($records);
                if($record['technical'] == $technical){
                    return true;
                }
                else
                    return false;
            }
        }
        else{ // Kiem tra theo ngay
            $records = Utils_RecordBrowserCommon::get_records('SCTV_MaintenanceDeployment', array('maintenance'=>$maintenance, 'technical'=>$technical, 'date'=>$date));
            if(empty($records))
                return false;
            else
                return true;
        }
    }
    private static function check_command_type($parts)
    {
        $result = null;

        $parts_count = count($parts);
        $part1 = self::pre_processing($parts[1]);

        if($parts_count == 4 && strpos($part1, 'DTBT') === 0){
			$result = 'NT';
        }
        elseif($parts_count >= 2){
            if(strpos($part1, 'TT') === 0){
                $result = 'TT';
            }
            elseif(strpos($part1, 'NGAYHEN') === 0){
                $result = 'NGAYHEN';
            }
        }

        return $result;
    }
	private static function valid_and_save_acceptance($msg_date, $msg_time, $contact, $results)
    {
		$dtbt = $results['DTBT']['DTBT'];
		if($dtbt == 'X'){
			return array(false, 'thieu doi tuong bao tri');
		}
		
		$tbbt = $results['TBBT'];
		$thc = $tbbt['THC'];
		$thc = $thc == 'X'?null:$thc;
		$net = $tbbt['NET'];
		$net = $net == 'X'?null:$net;
		if($thc == null && $net == null){
			return array(false, 'sai so luong THC/NET');
		}
		
        $mbt = $results['MBT'];

        if($mbt['STATUS'] == 3){// Da cho trang thai
            Utils_RecordBrowserCommon::update_record('SCTV_Maintenance', $mbt['ID'],
                array(
                    'status'=>1,
                    'acceptance_date'=>$msg_date,
                    'deployment_employee'=>$contact['id']
                )
            );

            $results = array(true);
        }
        else{
			Utils_RecordBrowserCommon::update_record('SCTV_Maintenance', $mbt['ID'],
                array(
                    'status'=>1,
                    'maintenance_date'=>$msg_date,
                    'maintenance_time'=>$msg_date . ' ' . $msg_time,
                    'acceptance_date'=>$msg_date,
                    'deployment_employee'=>$contact['id']
                )
            );

            $results = array(true);
        }

        return $results;
    }
    private static function valid_and_change_status($msg_date, $msg_time, $contact, $results){
		$status = $results['TT'];
		$mbt = $results['MBT'];
		if($status == 3){
			Utils_RecordBrowserCommon::update_record('SCTV_Maintenance', $mbt['ID'],
                array(
                    'status'=>$status,
					'maintenance_date'=>$msg_date,
                    'maintenance_time'=>$msg_date . ' ' . $msg_time
				));
		}
		else{
		    Utils_RecordBrowserCommon::update_record('SCTV_Maintenance', $mbt['ID'],
                array(
                    'status'=>$status
				));
		}

        Utils_RecordBrowserCommon::update_record('SCTV_MaintenanceStatusHistory', $mbt['ID'],
            array(
                'maintenance'=>$mbt['ID'],
                'date_time'=>$msg_date . ' ' . $msg_time,
                'employee'=>$contact['id'],
                'status'=>$status,
                'note'=>$results['GHICHU']
            )
        );

		return $results;
    }
    private static function valid_and_change_delivery_date($msg_date, $msg_time, $contact, $results){
        $mbt = $results['MBT'];
        Utils_RecordBrowserCommon::update_record('SCTV_Maintenance', $mbt['ID'],
            array(
                'delivery_date'=>$results['NGAY']
           )
        );

        Utils_RecordBrowserCommon::new_record('SCTV_MaintenanceDeliveryDateHistory', array(
            'maintenance'=>$mbt['ID'],
            'date_time'=>$msg_date . ' ' . $msg_time,
            'employee'=>$contact['id'],
            'delivery_date'=>$results['NGAY'],
            'note'=>$results['GHICHU']
        ));

        return $results;
    }
    public static function send_out($db, $receiver, $content, $code, $maintenance = null, $employee = null){
        if(mb_strlen($content) > 160){
            $content1 = mb_substr($content, 0, 160);
            $content2 = mb_substr($content, 160);
            if(!empty($content1)) self::send_out($db, $receiver, $content1, $code, $maintenance, $employee);
            if(!empty($content2)) self::send_out($db, $receiver, $content2, $code, $maintenance, $employee);
        }
        else{
            $result = pg_query_params($db,"select * from out_insert($1, $2, $3)",array($receiver, $content, $code));

            $results=pg_fetch_all($result);
            $row = array_shift($results);


            if($maintenance == null){
                Utils_RecordBrowserCommon::new_record('SCTV_MaintenanceSms', array(
                    'sms_id'=>$row['id'],
                    'receiver'=>$employee,
                    'content'=>$content,
                    'date'=>$row['request_date'],
                    'time'=>$row['request_date'] . ' ' . $row['request_time']
                ));
            }
            else{
                Utils_RecordBrowserCommon::new_record('SCTV_MaintenanceRequirementSms', array(
                    'in_out'=>0,
                    'maintenance'=>$maintenance,
                    'sms_id'=>$row['id'],
                    'employee'=>$employee,
                    'phone_number'=>$receiver,
                    'content'=>$content,
                    'date'=>$row['request_date'],
                    'time'=>$row['request_date'] . ' ' . $row['request_time']
                ));
            }
        }
    }
    public static function display_in_out($record, $nolink, $desc){
        return $record[$desc['id']] == 1?'Nhận':'Gửi';
    }
    public static function send_sms(){
        $dbconn=pg_connect("host=localhost port=5432 dbname=sms user=postgres password=admin");

        $ret = DB::Execute("SELECT * FROM sctv_maintenance_notify WHERE sms_sent = 'f' ORDER BY date_time asc LIMIT 4");
        while ($row = $ret->FetchRow()) {
            $maintenance = $row['maintenance'];
            $date_time = $row['date_time'];

            DB::Execute("update sctv_maintenance_notify SET sms_sent = 't' where maintenance = %d and date_time = %T", array($maintenance['id'], $date_time));
        }
    }
}
?>